package com.parking.mgr.common.factory;

import com.parking.mgr.common.pojo.base.node.BaseTreeNode;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName TreeBuildFactory
 * @Description 默认递归工具类，用于遍历有父子关系的节点，例如菜单树，字典树等等
 * @Auther: zhijianpu
 * @Date: 2023/5/22
 */
@Data
public class TreeBuildFactory<T extends BaseTreeNode> {

    /**
     * 顶级节点的父节点id(默认0)
     */
    private String rootId = "";

    /**
     * 树节点构造
     *
     * @param nodes
     * @return
     */
    public List<T> build(List<T> nodes) {
        List<T> resultTreeList = new ArrayList<>();
        for (T treeNode: nodes) {
            treeNode.setChildren(new ArrayList());
            if (Objects.isNull(treeNode) || Objects.equals(rootId, treeNode.getFkParentId())) {
                resultTreeList.add(treeNode);
            }
            for (T it : nodes) {
                if (Objects.equals(it.getFkParentId(), treeNode.getId())) {
                    treeNode.getChildren().add(it);
                }
            }
        }

        return resultTreeList;
    }

    /**
     * 当前节点为父节点id(默认当前节点的id)
     */
//    private String rootChildId = "";

    public List<T> buildChild(String currentId,List<T> nodes) {
        List<T> resultTreeList = new ArrayList<>();
        for (T treeNode: nodes) {
            treeNode.setChildren(new ArrayList());
            if (Objects.isNull(treeNode) || Objects.equals(currentId, treeNode.getFkParentId())) {
                resultTreeList.add(treeNode);
            }
            for (T it : nodes) {
                if (Objects.equals(it.getFkParentId(), treeNode.getId())) {
                    treeNode.getChildren().add(it);
                }
            }
        }

        return resultTreeList;
    }

}
